package main

import (
	"file-service/pkg"
	"fmt"
	"net/http"
	"strings"
)

func main() {
	run()
}
func run() {
	config := pkg.LoadConfig()
	message := pkg.NewMessage()
	handle := pkg.NewHTTPHandle(config, message)
	fmt.Println("-h 监听地址:", config.Host)
	fmt.Println("-p 文件存储目录:", config.Path)
	fmt.Println("-s 文件上传缓存大小(M):", config.MaxSize)
	var tempURL string
	if config.Host[0] == ':' {
		tempURL = fmt.Sprintf("http://127.0.0.1%s/upload.html", config.Host)
	} else {
		tempURL = fmt.Sprintf("http://%s/upload.html", config.Host)
	}
	showURL(config.Host)
	http.HandleFunc("/upload.html", handle.ToUpload)
	http.HandleFunc("/upload", handle.DoUpload)
	http.HandleFunc("/delete", handle.Delete)
	http.Handle("/", http.FileServer(http.Dir(config.Path)))
	//打开默认浏览器
	err := pkg.Open(tempURL)
	err = http.ListenAndServe(config.Host, nil)
	fmt.Println("err", err)
}

func showURL(host string) {
	fmt.Println("文件列表地址:")
	if host[0] == ':' {
		ips := pkg.AllIP4()
		i := strings.Index(host, ":")
		if i >= 0 {
			host = host[i:]
		}
		for _, ip := range ips {
			fmt.Printf("http://%s%s/\n", ip, host)
		}
	} else {
		fmt.Printf("http://%s/\n", host)
	}
}
